package com.quicksand.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;

import com.quicksand.push.SpringWebSocketHandler;

import java.util.Timer;
import java.util.TimerTask;

@Controller
public class WebsocketController {
    @Bean//这个注解会从Spring容器拿出Bean
    public SpringWebSocketHandler infoHandler() {
        return new SpringWebSocketHandler();
    }

    /**
     * 用户
     * @param request
     * @param response
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/websocket/userIndex")
    public ModelAndView userIndex(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        String username = request.getParameter("username");
        System.out.println(username + "登录");
//        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setAttribute("SESSION_USERNAME", username);
        }
//        Timer timer = new Timer();
//        timer.scheduleAtFixedRate(new TimerTask() {
//            public void run() {
//                infoHandler().sendMessageToUsers(new TextMessage("和哦哦"));
//            }
//        }, 1000, 5000);
        //response.sendRedirect("/quicksand/jsp/websocket.jsp");
        return new ModelAndView("/push/userIndex");
    }

    /**
     * 设备
     * @param request
     * @param response
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/websocket/sbIndex")
    public ModelAndView sbIndex(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        String username = request.getParameter("username");
        System.out.println(username + "登录");
//        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setAttribute("SESSION_USERNAME", username);
        }
        return new ModelAndView("/push/sbIndex");
    }

    @RequestMapping("/websocket/send")
    @ResponseBody
    public String send(HttpServletRequest request) {
        String username = request.getParameter("username");
        infoHandler().sendMessageToUser(username, new TextMessage("你好，测试！！！！"));
        return null;
    }


}